<template>
  <div>
    <el-row>
      <el-col class="content-header" :span="24">
        <div class="left"><span></span>{{ headerInfo.title }}</div>
        <div class="right" v-if="showRight">
          <el-button
            class="btn"
            v-show="showBtn"
            @click="addGoodsBtn"
            type="primary"
            size="small"
            >{{ headerInfo.rightInfo.btnName }}</el-button
          >
          <el-input
            size="small"
            v-model="iptVal"
            :placeholder="headerInfo.rightInfo.iptMessage"
            class="input-with-select"
            clearable
            @change="getList"
            @clear="getGoodsList"
          >
            <el-button
              size="small"
              slot="append"
              icon="el-icon-search"
              @click="getList"
            ></el-button>
          </el-input>
        </div>
      </el-col>
    </el-row>

    <!-- 添加商品对话框 -->
    <el-dialog
      title="添加物品"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :model="goodsForm"
        :rules="goodsRules"
        ref="goodsRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="物品名称" prop="Productname">
          <el-input v-model="goodsForm.Productname"></el-input>
        </el-form-item>
        <!-- 图片上传 -->
        <!-- action 表示图片要上传到的后台API地址 -->
        <!-- handlePreview 处理图片预览效果 -->
        <!-- handleRemove 处理移除图片的操作 -->
        <!-- headers  设置上传的请求头部 -->
        <!-- on-success 监听图片上传成功的事件 -->
        <el-form-item label="物品图片" prop="Productimage">
          <el-upload
            class="upload-demo imgbtn"
            action="http://localhost:8008/api/uploadImg"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :on-success="handleSuccess"
            :multiple="false"
            name="pic"
            ref="uploadImg"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <span slot="tip" class="el-upload__tip">只能上传一张图片</span>
            <el-input
              v-model="goodsForm.Productimage"
              v-show="false"
            ></el-input>
          </el-upload>
        </el-form-item>
        <!-- 物品描述 -->
        <el-form-item label="物品描述" prop="Describes">
          <el-input type="textarea" v-model="goodsForm.Describes"></el-input>
        </el-form-item>
        <!-- 发布人 -->
        <el-form-item label="发布人" prop="IssueUserid">
          <el-select
            v-model="goodsForm.IssueUserid"
            filterable
            placeholder="请选择发布人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.Username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addGoods">确 定</el-button>
      </span>

      <!-- 内置对话框，图片预览 -->
      <el-dialog
        width="30%"
        title="物品图片预览"
        :visible.sync="innerVisible"
        append-to-body
        class="imgVisible"
      >
        <img :src="goodsForm.Productimage" alt="" class="previewImg" />
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "Contentheader",
  props: ["headerInfo", "queryInfo"],
  data() {
    return {
      // 是否显示右侧输入框
      showRight: true,
      // 是否显示右侧按钮
      showBtn: true,
      // 输入框的数据
      iptVal: "",
      // 添加物品对话框的显示和隐藏
      dialogVisible: false,
      // 物品图片预览的显示和隐藏
      innerVisible: false,
      // 添加物品的数据
      goodsForm: {
        Productname: "", //物品名称
        Productimage: "", //物品图片
        Describes: "", // 物品描述
        IssueUserid: "", // 物品发布人
      },
      // 表单验证规则
      goodsRules: {
        Productname: [
          { required: true, message: "请输入物品名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        Productimage: [
          { required: true, message: "请上传物品图片", trigger: "change" },
        ],
        Describes: [
          { required: true, message: "请输入物品描述", trigger: "blur" },
        ],
        IssueUserid: [
          { required: true, message: "请输选择发布人", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    // 如果是个人信息路由组件，将右侧输入框隐藏
    if (this.$route.path == "/home/usermessage") {
      this.showRight = false;
    } else if (this.$route.path == "/home/usermanage") {
      // 如果是用户管理组件，将右侧按钮隐藏
      this.showBtn = false;
    } else {
      // 获取用户信息,用于添加物品
      this.$store.dispatch("usermanage/getUserLists");
    }
  },
  computed: {
    ...mapState("usermanage", ["userList"]),
    ...mapState("goodissus", ["addGoodMsg"]),
  },
  methods: {
    // 清空输入框事件
    getGoodsList() {
      // 如果是用户管理组件
      if (this.$route.path == "/home/usermanage") {
        this.$emit("getUserList");
      } else {
        this.$store.dispatch(
          "goodissus/getGoodsLists",
          JSON.stringify(this.queryInfo)
        );
      }
    },
    // 搜索按钮
    getList() {
      // 如果是物品发布页，则搜索物品信息
      if (this.$route.path == "/home/goodissus") {
        this.$store.dispatch("goodissus/getSearchGoodsLists", this.iptVal);
      }
      // 如果是个用户管理页，则搜索用户名
      if (this.$route.path == "/home/usermanage") {
        this.$store.dispatch("usermanage/searchUserLists", this.iptVal);
      }
    },
    // 对话框打开事件
    addGoodsBtn() {
      this.dialogVisible = true;
    },
    // 对话框关闭事件
    handleClose() {
      this.$refs.goodsRuleForm.resetFields(); //重置表单
      //移除图片
      let imglist = document.getElementsByClassName("el-upload-list")[0];
      if (imglist.children.length >= 1) {
        imglist.removeChild(imglist.firstChild);
      }
      this.dialogVisible = false;
    },

    // 添加物品事件
    addGoods() {
      this.$refs.goodsRuleForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        // 通知vuex调用axios接口
        this.$store.dispatch(
          "goodissus/addGoodsLists",
          JSON.stringify(this.goodsForm)
        );
        this.handleClose();
      });
    },
    //#region  图片上传功能
    // 处理移除图片的操作
    handleRemove() {
      this.goodsForm.Productimage = "";
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      //移除上一次上传的图片
      let imglist = document.getElementsByClassName("el-upload-list")[0];
      if (imglist.children.length >= 2) {
        imglist.removeChild(imglist.firstChild);
      }
      // 把图片路径保存起来
      this.goodsForm.Productimage =
        "http://localhost:8008/" +
        response.file.path.split("\\")[0] +
        "/" +
        response.file.path.split("\\")[1];
    },
    // 处理图片预览效果
    handlePreview() {
      this.innerVisible = true;
    },
    //#endregion
  },
  watch: {
    //监听vuex中的数据变化
    addGoodMsg: {
      handler(newVal) {
        if (newVal.affectedRows > 0) {
          this.$message.success("添加物品成功！");
          // 通知Goodissus组件刷新数据列表  传递分页数据 queryInfo
          this.$store.dispatch(
            "goodissus/getGoodsLists",
            JSON.stringify(this.queryInfo)
          );
          // 重新获取物品条数
          this.$store.dispatch("goodissus/totalNumGoodsLists");
        } else {
          this.$message.error("添加物品失败！");
        }
      },
    },
  },
};
</script>

<style lang="less" scoped>
@Headerheight: 60px; //头部高度
.content-header {
  background: #fff;
  line-height: @Headerheight;
  .left {
    float: left;
    margin-left: 20px;
    span {
      padding: 0 1px;
      background: #265bcd;
      margin-right: 5px;
    }
  }
  .right {
    float: right;
    margin-right: 30px;
    width: 270px;
    height: @Headerheight;
    position: relative;
    .el-input {
      width: 200px;
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
    .btn {
      margin-right: 10px;
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}
.el-button {
  outline: none;
}
.imgbtn,
.el-select {
  float: left;
}
.imgVisible {
  text-align: center;
  .previewImg {
    max-height: 400px;
    max-width: 100%;
  }
}
</style>
